package com.sgl.gk.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.sg.comm.common.Ret;
import com.sg.comm.opcuav2.NodeDTOV2;
import com.sg.comm.opcuav2.OpcUaReadReqV2;
import com.sg.comm.opcuav2.OpcUaWriteReqV2;
import com.sg.comm.opcuav2.batch.BatchReadDTO;
import com.sg.comm.opcuav2.single.ReadByNodeReq;
import com.sg.comm.service.OpcUaServiceV2;
import com.sgl.common.core.domain.AjaxResult;
import com.sgl.common.utils.StringUtils;
import com.sgl.gk.controller.vo.*;
import com.sgl.gk.dict.StationDict;
import com.sgl.gk.domain.*;
import com.sgl.gk.domain.plc.Node;
import com.sgl.gk.domain.plc.OpcUa;
import com.sgl.gk.domain.plc.OpcUaList;
import com.sgl.gk.mapper.*;
import com.sgl.gk.scheduled.ScheduledTask;
import com.sgl.gk.scheduled.vo.ServiceData;
import com.sgl.gk.scheduled.vo.SocketDataVo;
import com.sgl.gk.service.GkSettingLogService;
import com.sgl.gk.service.GkStationConfigureTemplateService;
import com.sgl.gk.tools.BarCodeTool;
import com.sgl.gk.tools.OpcUATool;
import com.sgl.gk.tools.ReadOpcUaNodeInfoTool;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author:xec
 * @date:2022/11/25 11:44
 **/
@Service
@Slf4j
public class GkStationConfigureTemplateServiceImpl implements GkStationConfigureTemplateService {

    @Autowired
    GkStationConfigureTemplateMapper gkStationConfigureTemplateMapper;

    @Autowired
    GkStationMapper gkStationMapper;

    @Autowired
    GkStationConfigurationMapper getGkStationConfigurationMapper;

    @Autowired
    GkStationConfigureTemplateInfoMapper gkStationConfigureTemplateInfoMapper;

    @Autowired
    GkStationConfigurationMapper gkStationConfigurationMapper;

    @Autowired
    GkSignalCommunicationMapper gkSignalCommunicationMapper;

    @Autowired
    GkSettingLogService gkSettingLogService;

    @Autowired
    GkProductMapper gkProductMapper;

    @Autowired
    GkReservedInfoMapper gkReservedInfoMapper;

    @Autowired
    GkProductionLineMapper gkProductionLineMapper;

    @DubboReference(version = "1.0.0", url = "dubbo://127.0.0.1:20880", check = false, timeout = 15000)
    private OpcUaServiceV2 opcUaServiceV2;

    @Value("${communication.mode}")
    public String communication;

    @Override
    public List<GkStationConfigureTemplate> list(GkStationConfigureTemplate gkStationConfigureTemplate) {
        if (gkStationConfigureTemplate.getProductionLineId() == null && StringUtils.isEmpty(gkStationConfigureTemplate.getName())) {
            return new ArrayList<>();
        }
        List<GkStationConfigureTemplate> gkStationConfigureTemplates = gkStationConfigureTemplateMapper.list(gkStationConfigureTemplate);
        if (gkStationConfigureTemplates == null || gkStationConfigureTemplates.size() == 0) {
            return new ArrayList<>();
        }
        Map<Long, List<Long>> stationIdListMap = new HashMap<>();
        List<Long> allStationIds = new ArrayList<>();
        for (GkStationConfigureTemplate gkStationConfigureTemplate1 : gkStationConfigureTemplates) {
            List<Long> stationIds = new ArrayList<>();
            String[] split = gkStationConfigureTemplate1.getStationIdList().split(",");
            for (String s : split) {
                if (!StringUtils.isEmpty(s)) {
                    long e = Long.parseLong(s);
                    stationIds.add(e);
                    allStationIds.add(e);
                }
            }
            stationIdListMap.put(gkStationConfigureTemplate1.getId(), stationIds);
        }
        allStationIds = allStationIds.stream().distinct().collect(Collectors.toList());
        if (allStationIds != null && allStationIds.size() > 0) {
            List<GkStation> gkStations = gkStationMapper.selectInfosByIds(allStationIds);
            for (GkStationConfigureTemplate gkStationConfigureTemplate1 : gkStationConfigureTemplates) {
                List<String> stationNameList = new ArrayList<>();
                for (GkStation gkStation : gkStations) {
                    List<Long> list = stationIdListMap.get(gkStationConfigureTemplate1.getId());
                    for (Long aLong : list) {
                        if (gkStation.getId().longValue() == aLong.longValue()) {
                            stationNameList.add(gkStation.getName());
                        }
                    }
                }
                gkStationConfigureTemplate1.setStationIdList(StringUtils.join(stationNameList, ","));
            }
        }
        List<Long> productionLineIds = gkStationConfigureTemplates.stream().map(GkStationConfigureTemplate::getProductionLineId).collect(Collectors.toList());
        List<GkProductionLineVo> gkProductionLineVos = gkProductionLineMapper.selectInfoByIds(productionLineIds);
        for (GkProductionLineVo gkProductionLineVo : gkProductionLineVos) {
            for (GkStationConfigureTemplate stationConfigureTemplate : gkStationConfigureTemplates) {
                if (gkProductionLineVo.getId().longValue() == stationConfigureTemplate.getProductionLineId().longValue()) {
                    stationConfigureTemplate.setProductionLineName(gkProductionLineVo.getName());
                }
            }
        }
        return gkStationConfigureTemplates;
    }

    @Override
    public AjaxResult edit(GkStationConfigureTemplate gkStationConfigureTemplate) {
        GkStationConfigureTemplate gkStationConfigureTemplate1 = new GkStationConfigureTemplate();
        gkStationConfigureTemplate1.setProductionLineId(gkStationConfigureTemplate.getProductionLineId());
        List<GkStationConfigureTemplate> gkStationConfigureTemplates = gkStationConfigureTemplateMapper.list(gkStationConfigureTemplate1);
        for (GkStationConfigureTemplate stationConfigureTemplate : gkStationConfigureTemplates) {
            if (StringUtils.equals(stationConfigureTemplate.getName(), gkStationConfigureTemplate.getName())) {
                return AjaxResult.error("模板名称重复");
            }
        }
        int row = gkStationConfigureTemplateMapper.edit(gkStationConfigureTemplate);
        return AjaxResult.success();
    }

    @Transactional
    @Override
    public AjaxResult saveTemplate(SaveTemplateVo saveTemplateVo) {
        GkStationConfigureTemplate gkStationConfigureTemplate1 = new GkStationConfigureTemplate();
        gkStationConfigureTemplate1.setProductionLineId(saveTemplateVo.getProductionLineId());
        List<GkStationConfigureTemplate> gkStationConfigureTemplates = gkStationConfigureTemplateMapper.list(gkStationConfigureTemplate1);
        for (GkStationConfigureTemplate gkStationConfigureTemplate : gkStationConfigureTemplates) {
            if (StringUtils.equals(gkStationConfigureTemplate.getName().trim(), saveTemplateVo.getName().trim())) {
                return AjaxResult.error("模板名称重复");
            }
        }
        if (saveTemplateVo.getGkStationConfigurations() == null || saveTemplateVo.getGkStationConfigurations().size() == 0) {
            return AjaxResult.error("无可存模板参数");
        }
        List<GkStationConfiguration> gkStationConfigurations1 = saveTemplateVo.getGkStationConfigurations();
        List<Long> stationIds1 = gkStationConfigurations1.stream().map(GkStationConfiguration::getStationId).distinct().collect(Collectors.toList());
        List<GkStation> gkStations1 = gkStationMapper.selectInfosByIds(stationIds1);
        if (!BarCodeTool.inspect(gkStationConfigurations1,gkStations1)) {
            return AjaxResult.error(BarCodeTool.msg);
        }
        Date date = new Date();
        GkStationConfigureTemplate gkStationConfigureTemplate = new GkStationConfigureTemplate();
        gkStationConfigureTemplate.setName(saveTemplateVo.getName());
        gkStationConfigureTemplate.setConfigureType(StationDict.SAVEUNCONFIGURED.value);
        gkStationConfigureTemplate.setProductionLineId(saveTemplateVo.getProductionLineId());
        gkStationConfigureTemplate.setLastModifyAt(date);
        gkStationConfigureTemplate.setCreateAt(date);
        List<GkStationConfiguration> gkStationConfigurations = saveTemplateVo.getGkStationConfigurations();
        Map<Long, List<GkStationConfiguration>> collect = gkStationConfigurations.stream().collect(Collectors.groupingBy(GkStationConfiguration::getStationId));
        Set<Long> longs = collect.keySet();
        gkStationConfigureTemplate.setStationIdList(StringUtils.join(longs, ","));
        int row = gkStationConfigureTemplateMapper.add(gkStationConfigureTemplate);
        GkStation gkStation = new GkStation();
        gkStation.setProductionLineId(saveTemplateVo.getProductionLineId());
        List<GkStationVo> gkStationVos = gkStationMapper.list(gkStation);
        List<Long> stationIds = gkStationVos.stream().map(GkStationVo::getId).collect(Collectors.toList());
        List<GkStationConfiguration> gkStationConfigurationList = getGkStationConfigurationMapper.selectInfoByStations(stationIds.toArray(new Long[0]));
        List<GkStationConfiguration> gkStationConfigurationsByType2 = gkStationConfigurationList.stream().filter(gkStationConfiguration -> gkStationConfiguration.getType() == 2).collect(Collectors.toList());
        if (row > 0) {
            Long templateId = gkStationConfigureTemplateMapper.MaxId();
            List<GkStationConfigureTemplateInfo> list = new ArrayList<>();
            gkStationConfigurations.addAll(gkStationConfigurationsByType2);
            for (GkStationConfiguration gkStationConfiguration : gkStationConfigurations) {
                GkStationConfigureTemplateInfo gkStationConfigureTemplateInfo = new GkStationConfigureTemplateInfo();
                gkStationConfigureTemplateInfo.setConfigureTemplateId(templateId);
                gkStationConfigureTemplateInfo.setStationConfigurationId(gkStationConfiguration.getId());
                // 保存实时值为模板
                gkStationConfigureTemplateInfo.setValue(gkStationConfiguration.getDefaultValue());
                // 保存设置值为模板
//                gkStationConfigureTemplateInfo.setValue(gkStationConfiguration.getSaveValue());
                gkStationConfigureTemplateInfo.setCreateAt(date);
                gkStationConfigureTemplateInfo.setLastModifyAt(date);
                list.add(gkStationConfigureTemplateInfo);
            }
            gkStationConfigureTemplateInfoMapper.saveList(list);
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    @Override
    public AjaxResult selectInfoByTemplateId(Long templateId) {
        // 得到模板信息
        GkStationConfigureTemplate gkStationConfigureTemplate = gkStationConfigureTemplateMapper.selectInfoById(templateId);
        if (gkStationConfigureTemplate==null){
            return AjaxResult.error("无模板信息");
        }
        List<GkProductionLineVo> gkProductionLineVos = gkProductionLineMapper.selectInfoByIds(Collections.singletonList(gkStationConfigureTemplate.getProductionLineId()));
        // 根据模板信息中的产线id找出他下面的所有工位
        List<GkStation> gkStations = gkStationMapper.selectByProductionIds(Collections.singletonList(gkStationConfigureTemplate.getProductionLineId()));
        gkStations = gkStations.stream().sorted(Comparator.comparing(GkStation::getDefaultStation).reversed()).collect(Collectors.toList());
        List<Long> stationIds = new ArrayList<>();
        List<Long> collect = new ArrayList<>();
        for (GkStation gkStation : gkStations) {
            gkStation.setConfigureType(gkStationConfigureTemplate.getConfigureType());
            stationIds.add(gkStation.getId());
            collect.add(gkStation.getSignalCommunicationId());
        }
        collect = collect.stream().distinct().collect(Collectors.toList());
        OpcUaReadReqV2 opcUaReadReqV2 = new OpcUaReadReqV2();
        List<GkSignalCommunication> gkSignalCommunications = gkSignalCommunicationMapper.selectInfoByIds(collect);
        if (gkSignalCommunications != null && gkSignalCommunications.size() > 0) {
            for (GkSignalCommunication gkSignalCommunication : gkSignalCommunications) {
                if (gkSignalCommunication.getCommunicationProtocol() != null) {
                    opcUaReadReqV2.setUid(gkSignalCommunication.getCommunicationProtocol());
                }
            }
        }
        BufferedWriter bufferedWriter = ScheduledTask.bufferedWriter;
        BufferedReader bufferedReader = ScheduledTask.bufferedReader;
        List<GkStationConfigurationVo> gkStationConfigurationVos = new ArrayList<>();

        List<TemplateSaveParamInfosVo> saveParamInfosVoList = new ArrayList<>();
        List<GkStationConfiguration> gkStationConfigurationList = gkStationConfigurationMapper.selectInfoByType1Stations(stationIds);
        try {
            BatchReadDTO listRet = null;
            List<SocketDataVo> socketDataVos = new ArrayList<>();
            try {
                if (communication.equals("socket")) {
                    bufferedWriter.write(opcUaReadReqV2.getUid() + "\n");
                    bufferedWriter.flush();
                    String s = bufferedReader.readLine();
                    JSONArray objects = JSON.parseArray(s);
                    for (Object object : objects) {
                        SocketDataVo socketDataVo = JSON.parseObject(object.toString(), SocketDataVo.class);
                        socketDataVos.add(socketDataVo);
                    }
                } else if (communication.equals("plc")) {
                    ReadByNodeReq readByNodeReq = new ReadByNodeReq();
                    readByNodeReq.setUid(opcUaReadReqV2.getUid());
                    List<NodeDTOV2> nodeDTOV2List = GetNodeDTO2List(null, gkStationConfigurationList, gkStations, gkProductionLineVos, opcUaReadReqV2.getUid());
                    readByNodeReq.setNodeDTOV2List(nodeDTOV2List);
                    Ret<BatchReadDTO> batchReadDTORet = opcUaServiceV2.readDataByNodeList(readByNodeReq);
                    listRet = batchReadDTORet.getData();
//                    listRet = opcUaServiceV2.readData(opcUaReadReqV2).getData();
                }
            } catch (Exception e) {
                log.error("PLC连接异常");
            }

            List<NodeDTOV2> data = new ArrayList<>();
            if (communication.equals("socket")) {
                for (SocketDataVo socketDataVo : socketDataVos) {
                    List<ServiceData> nodeList = socketDataVo.getNodeList();
                    for (ServiceData serviceData : nodeList) {
                        NodeDTOV2 nodeDTOV2 = new NodeDTOV2();
                        nodeDTOV2.setNodeValue(serviceData.getNodeValue());
                        nodeDTOV2.setNodeType(serviceData.getNodeType());
                        nodeDTOV2.setNodeName(serviceData.getNodeName());
                        nodeDTOV2.setNodeId(serviceData.getNodeId());
                        nodeDTOV2.setDisplayName(serviceData.getDisplayName());
                        nodeDTOV2.setStatusCode(0l);
                        data.add(nodeDTOV2);
                    }
                }
            } else if (communication.equals("plc")) {
                if (listRet != null && listRet.getIsConn()) {
                    data = listRet.getDtoList();
                }
            }
            List<GkStationConfiguration> gkStationConfigurationList1 = gkStationConfigurationMapper.selectInfoByStations(stationIds.toArray(new Long[0]));


            // 根据模板id找出模板信息数组
            List<GkStationConfigureTemplateInfo> gkStationConfigureTemplateInfos = gkStationConfigureTemplateInfoMapper.selectInfoByConfigureTemplateId(templateId);
            // todo 找到模板没有添加的变量进行添加
            List<GkStationConfigureTemplateInfo> gkStationConfigureTemplateInfos1 = new ArrayList<>();
            for (GkStationConfiguration gkStationConfiguration : gkStationConfigurationList1) {
                int flag = 0;
                for (GkStationConfigureTemplateInfo gkStationConfigureTemplateInfo : gkStationConfigureTemplateInfos) {
                    if (gkStationConfiguration.getId().longValue()== gkStationConfigureTemplateInfo.getStationConfigurationId().longValue()){
                        flag = 1;
                    }
                }
                if (flag == 0){
                    GkStationConfigureTemplateInfo e = new GkStationConfigureTemplateInfo();
                    e.setConfigureTemplateId(templateId);
                    e.setStationConfigurationId(gkStationConfiguration.getId());
                    e.setValue(gkStationConfiguration.getDefaultValue());
                    Date date = new Date();
                    e.setLastModifyAt(date);
                    e.setCreateAt(date);
                    e.setTempToUse(1);
                    e.setTempConfigName(gkStationConfiguration.getDisplayName());
                    gkStationConfigureTemplateInfos1.add(e);
                }
            }
            if (CollUtil.isNotEmpty(gkStationConfigureTemplateInfos1)){
                gkStationConfigureTemplateInfoMapper.saveList(gkStationConfigureTemplateInfos1);
            }

            gkStationConfigureTemplateInfos = gkStationConfigureTemplateInfoMapper.selectInfoByConfigureTemplateId(templateId);
            for (GkStationConfiguration gkStationConfiguration : gkStationConfigurationList) {
                for (GkStationConfigureTemplateInfo gkStationConfigureTemplateInfo : gkStationConfigureTemplateInfos) {
                    if (gkStationConfigureTemplateInfo.getStationConfigurationId().longValue() == gkStationConfiguration.getId().longValue()) {
                        GkStationConfigurationVo gkStationConfigurationVo = new GkStationConfigurationVo();
                        gkStationConfigurationVo.setStationId(gkStationConfiguration.getStationId());
                        gkStationConfigurationVo.setDataType(gkStationConfiguration.getDataType());
                        gkStationConfigurationVo.setId(gkStationConfiguration.getId());
                        gkStationConfigurationVo.setType(gkStationConfiguration.getType());
                        gkStationConfigurationVo.setCheckLength(gkStationConfiguration.getCheckLength());
                        gkStationConfigurationVo.setCreateAt(gkStationConfiguration.getCreateAt());
                        gkStationConfigurationVo.setDisplayName(gkStationConfiguration.getDisplayName());
                        gkStationConfigurationVo.setNameSpaces(gkStationConfiguration.getNameSpaces());
                        gkStationConfigurationVo.setToUse(gkStationConfiguration.getToUse());
                        gkStationConfigurationVo.setVariableAddress(gkStationConfiguration.getVariableAddress());
                        gkStationConfigurationVo.setVariableComments(gkStationConfiguration.getVariableComments());
                        gkStationConfigurationVo.setVariableIndex(gkStationConfiguration.getVariableIndex());
                        gkStationConfigurationVo.setVariableName(gkStationConfiguration.getVariableName());
                        gkStationConfigurationVo.setVariableRemarks(gkStationConfiguration.getVariableRemarks());
                        gkStationConfigurationVo.setTempToUse(gkStationConfigureTemplateInfo.getTempToUse());
                        gkStationConfigurationVo.setTempInfoId(gkStationConfigureTemplateInfo.getId());
                        if (StringUtils.isNotEmpty(gkStationConfigureTemplateInfo.getTempConfigName())){
                            gkStationConfigurationVo.setTempConfigName(gkStationConfigureTemplateInfo.getTempConfigName());
                        }else {
                            gkStationConfigurationVo.setTempConfigName(gkStationConfigurationVo.getDisplayName());
                        }
                        for (NodeDTOV2 datum : data) {
                            Object obj = new Object();
                            if (datum.getNodeValue() != null) {
                                int i = datum.getNodeValue().toString().replace("}", "").indexOf("=");
                                if (i > 0) {
                                    obj = datum.getNodeValue().toString().replace("}", "").substring(i + 1);
                                } else {
                                    obj = datum.getNodeValue();
                                }
                            } else {
                                obj =  null;
                            }
                            String nodeName = new String();
                            for (GkStation gkStation : gkStations) {
                                if (gkStation.getId().longValue() == gkStationConfiguration.getStationId().longValue()) {
                                    if (gkStationConfiguration.getType() == 1) {
                                        nodeName = "DB_RECIPE." + ((gkStation.getCode() == null || gkStation.getCode().equals("")) ? "" : (gkStation.getCode() + ".")) + gkStationConfiguration.getVariableName();
                                    }
                                    if (gkStationConfiguration.getType() == 2) {
                                        for (GkProductionLineVo gkProductionLineVo : gkProductionLineVos) {
                                            if (gkStation.getProductionLineId().longValue() == gkProductionLineVo.getId().longValue()) {
                                                nodeName = gkProductionLineVo.getCode() + "." + ((gkStation.getCode() == null || gkStation.getCode().equals("")) ? "" : (gkStation.getCode() + ".")) + gkStationConfiguration.getVariableName();
                                            }
                                        }
                                    }
                                    if (gkStationConfiguration.getType() == 3) {
                                        // 写入交互变量类型  3写
                                        nodeName = "data_pc_plc.pc_reply." + gkStationConfiguration.getVariableName();
                                    }
                                    if (gkStationConfiguration.getType() == 4) {
                                        // 读取交互变量类型  4读
                                        nodeName = "data_pc_plc.plc_request." + gkStationConfiguration.getVariableName();
                                    }
                                    if (datum.getDisplayName().equals(nodeName)) {
                                        gkStationConfigurationVo.setDefaultValue(obj);
                                    }
                                }
                            }
                        }
                        Object newobj = new Object();
                        if (gkStationConfiguration.getDataType().equals("boolean")) {
                            if (gkStationConfigureTemplateInfo.getValue() == null || gkStationConfigureTemplateInfo.getValue().equals("false")) {
                                newobj = Boolean.FALSE;
                            } else {
                                newobj = Boolean.TRUE;
                            }
                        } else {
                            newobj = gkStationConfigureTemplateInfo.getValue() == null ? "" : gkStationConfigureTemplateInfo.getValue();
                        }
                        gkStationConfigurationVo.setSaveValue(newobj);
                        gkStationConfigurationVos.add(gkStationConfigurationVo);
                    }
                }
            }

            List<GkStationConfigurationVo> saveConfig = gkStationConfigurationMapper.selectInfoByType2StationIds(stationIds);
            for (GkStationConfigurationVo gkStationConfigurationVo : saveConfig) {
                for (GkStationConfigureTemplateInfo gkStationConfigureTemplateInfo : gkStationConfigureTemplateInfos) {
                    if (gkStationConfigurationVo.getId().longValue()== gkStationConfigureTemplateInfo.getStationConfigurationId().longValue()){
                        // 表示id一样
                        TemplateSaveParamInfosVo templateSaveParamInfosVo = new TemplateSaveParamInfosVo();
                        templateSaveParamInfosVo.setTempInfoId(gkStationConfigureTemplateInfo.getId());
                        templateSaveParamInfosVo.setTempToUse(gkStationConfigureTemplateInfo.getTempToUse());
                        if (StringUtils.isNotEmpty(gkStationConfigureTemplateInfo.getTempConfigName())){
                            templateSaveParamInfosVo.setTempConfigName(gkStationConfigureTemplateInfo.getTempConfigName());
                        }else {
                            templateSaveParamInfosVo.setTempConfigName(gkStationConfigurationVo.getDisplayName());
                        }
                        BeanUtils.copyProperties(gkStationConfigurationVo, templateSaveParamInfosVo, new String[]{"tempInfoId", "tempToUse","tempConfigName"});
                        saveParamInfosVoList.add(templateSaveParamInfosVo);
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        Map<Long, List<GkStationConfigurationVo>> listMap = gkStationConfigurationVos.parallelStream().collect(Collectors.groupingBy(GkStationConfigurationVo::getStationId));
        Map<Long, List<TemplateSaveParamInfosVo>> saveConfigMap = saveParamInfosVoList.parallelStream().collect(Collectors.groupingBy(TemplateSaveParamInfosVo::getStationId));
        List<Map<String, Object>> mapList = new ArrayList<>();
        int count = 0;
        for (GkStation gkStation : gkStations) {
            Map<String, Object> map = new HashMap<>();
            map.put("stationId", gkStation.getId());
            map.put("stationName", gkStation.getName());
            map.put("stationCode", gkStation.getCode());
            map.put("configureType", gkStation.getConfigureType());
            map.put("stationConfigurations", listMap.size() > 0 ? listMap.get(gkStation.getId()) : new ArrayList<>());
            map.put("showConfigurations",listMap.size()>0?listMap.get(gkStation.getId()).stream().filter(gks->gks.getTempToUse()!=0).collect(Collectors.toList()):new ArrayList<>());
            map.put("saveConfigurations", saveConfigMap.size() > 0 ? saveConfigMap.get(gkStation.getId()) : new ArrayList<>());
            if (gkStation.getConfigureType() != 3) {
                count += 1;
            }
            mapList.add(map);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("noConfigurationNum", count);
        map.put("stationInfos", mapList);
        return AjaxResult.success(map);
    }

    private List<NodeDTOV2> GetNodeDTO2List(List<GkStationConfigurationVo> list,List<GkStationConfiguration> gkStationConfigurationList, List<GkStation> gkStations,List<GkProductionLineVo> gkProductionLineVos,String uId){
        List<NodeDTOV2> nodeDTOV2List = new ArrayList<>();
        OpcUaList opcUaList = ReadOpcUaNodeInfoTool.GetOpcUaList();
        List<OpcUa> uaList = opcUaList.getOpcUaList();
        List<Node> fileNodeList = new ArrayList<>();
        for (OpcUa opcUa : uaList) {
            if (opcUa.getUid().equals(uId)){
                fileNodeList = opcUa.getNodeList();
            }
        }
        if (CollUtil.isNotEmpty(list)) {
            for (GkStationConfigurationVo gkStationConfigurationVo : list) {
                NodeDTOV2 nodeDTOV2 = new NodeDTOV2();
                GkStation gkStation1 = new GkStation();
                for (GkStation gkStation : gkStations) {
                    gkStation1 = gkStation;
                }
                String nodeName = new String();
                if (gkStationConfigurationVo.getType() == 1) {
                    nodeName = "DB_RECIPE." + ((gkStation1.getCode() == null || gkStation1.getCode().equals("")) ? "" : (gkStation1.getCode() + ".")) + gkStationConfigurationVo.getVariableName();
                }
                if (gkStationConfigurationVo.getType() == 2) {
                    for (GkProductionLineVo gkProductionLineVo : gkProductionLineVos) {
                        if (gkStation1.getProductionLineId().longValue() == gkProductionLineVo.getId().longValue()) {
                            if (!StringUtils.isEmpty(gkStation1.getDataSource())) {
                                nodeName = gkStation1.getDataSource() + "." + ((gkStation1.getCode() == null || gkStation1.getCode().equals("")) ? "" : (gkStation1.getCode() + ".")) + gkStationConfigurationVo.getVariableName();
                            } else {
                                nodeName = gkProductionLineVo.getCode() + "." + ((gkStation1.getCode() == null || gkStation1.getCode().equals("")) ? "" : (gkStation1.getCode() + ".")) + gkStationConfigurationVo.getVariableName();
                            }
                        }
                    }
                }
                if (CollUtil.isNotEmpty(fileNodeList)) {
                    for (Node node : fileNodeList) {
                        if (node.getDisplayName().equals(nodeName)) {
                            nodeDTOV2.setNodeId(node.getNodeId());
                            nodeDTOV2.setNodeType(node.getNodeType());
                            nodeDTOV2.setDisplayName(nodeName);
                            nodeDTOV2.setNodeName(node.getNodeName());
                            nodeDTOV2List.add(nodeDTOV2);
                            break;
                        }
                    }
                }
            }
        }else if (CollUtil.isNotEmpty(gkStationConfigurationList)){
            Map<Long, List<GkStationConfiguration>> stationConfigMap = gkStationConfigurationList.parallelStream().collect(Collectors.groupingBy(GkStationConfiguration::getStationId));
            for (GkStation gkStation : gkStations) {
                List<GkStationConfiguration> gkStationConfigurations = stationConfigMap.get(gkStation.getId().longValue());
                if (CollUtil.isNotEmpty(gkStationConfigurations)) {
                    for (GkStationConfiguration gkStationConfigurationVo : gkStationConfigurations) {
                        NodeDTOV2 nodeDTOV2 = new NodeDTOV2();
                        GkStation gkStation1 = gkStation;
                        String nodeName = new String();
                        if (gkStationConfigurationVo.getType() == 1) {
                            nodeName = "DB_RECIPE." + ((gkStation1.getCode() == null || gkStation1.getCode().equals("")) ? "" : (gkStation1.getCode() + ".")) + gkStationConfigurationVo.getVariableName();
                        }
                        if (gkStationConfigurationVo.getType() == 2) {
                            for (GkProductionLineVo gkProductionLineVo : gkProductionLineVos) {
                                if (gkStation1.getProductionLineId().longValue() == gkProductionLineVo.getId().longValue()) {
                                    if (!StringUtils.isEmpty(gkStation1.getDataSource())) {
                                        nodeName = gkStation1.getDataSource() + "." + ((gkStation1.getCode() == null || gkStation1.getCode().equals("")) ? "" : (gkStation1.getCode() + ".")) + gkStationConfigurationVo.getVariableName();
                                    } else {
                                        nodeName = gkProductionLineVo.getCode() + "." + ((gkStation1.getCode() == null || gkStation1.getCode().equals("")) ? "" : (gkStation1.getCode() + ".")) + gkStationConfigurationVo.getVariableName();
                                    }
                                }
                            }
                        }
                        if (CollUtil.isNotEmpty(fileNodeList)) {
                            for (Node node : fileNodeList) {
                                if (node.getDisplayName().equals(nodeName)) {
                                    nodeDTOV2.setNodeId(node.getNodeId());
                                    nodeDTOV2.setNodeType(node.getNodeType());
                                    nodeDTOV2.setDisplayName(nodeName);
                                    nodeDTOV2.setNodeName(node.getNodeName());
                                    nodeDTOV2List.add(nodeDTOV2);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        return nodeDTOV2List;
    }

    @Override
    @Transactional
    public AjaxResult removeByIds(Long[] ids) {
        int row = gkStationConfigureTemplateMapper.removeByIds(ids);
        if (row > 0) {
            row = gkStationConfigureTemplateInfoMapper.deleteByTemplateIds(ids);
            if (row > 0) {
                return AjaxResult.success();
            }
        }
        return AjaxResult.error();
    }

    @Override
    public AjaxResult setParametersByTemplateId(Long templateId) {
        List<GkStationConfigureTemplateInfo> gkStationConfigureTemplateInfos = gkStationConfigureTemplateInfoMapper.selectInfoByConfigureTemplateId(templateId);
        gkStationConfigureTemplateInfos = gkStationConfigureTemplateInfos.stream().filter(gkStationTemp->gkStationTemp.getTempToUse()!=0).collect(Collectors.toList());
        GkStationConfigureTemplate gkStationConfigureTemplate = gkStationConfigureTemplateMapper.selectInfoById(templateId);
        List<GkStation> gkStations = gkStationMapper.selectByProductionIds(Collections.singletonList(gkStationConfigureTemplate.getProductionLineId()));
        List<Long> stationIds = new ArrayList<>();
        List<Long> signalCommunicationIds = new ArrayList<>();
        for (GkStation gkStation : gkStations) {
            stationIds.add(gkStation.getId());
            signalCommunicationIds.add(gkStation.getSignalCommunicationId());
        }
        // todo 根据模板一键配置设置参数   定位
        signalCommunicationIds = signalCommunicationIds.stream().distinct().collect(Collectors.toList());
        List<GkStationConfiguration> gkStationConfigurationList = gkStationConfigurationMapper.selectInfoByType1Stations(stationIds);
        List<GkProductionLineVo> gkProductionLineVos = gkProductionLineMapper.selectInfoByIds(Collections.singletonList(gkStationConfigureTemplate.getProductionLineId()));
        List<GkSignalCommunication> gkSignalCommunications = gkSignalCommunicationMapper.selectInfoByIds(signalCommunicationIds);
        OpcUaWriteReqV2 opcUaWriteReqV2 = new OpcUaWriteReqV2();
        if (gkSignalCommunications != null && gkSignalCommunications.size() > 0) {
            for (GkSignalCommunication gkSignalCommunication : gkSignalCommunications) {
                if (gkSignalCommunication.getCommunicationProtocol() != null) {
                    opcUaWriteReqV2.setUid(gkSignalCommunication.getCommunicationProtocol());
                }
            }
        }
        List<NodeDTOV2> writeNodeList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        String productName = "";
        OpcUaList opcUaList = ReadOpcUaNodeInfoTool.GetOpcUaList();
        List<OpcUa> uaList = opcUaList.getOpcUaList();
        List<Node> fileNodeList = new ArrayList<>();
        for (OpcUa opcUa : uaList) {
            if (opcUa.getUid().equals(opcUaWriteReqV2.getUid())){
                fileNodeList = opcUa.getNodeList();
            }
        }
        for (GkStationConfiguration gkStationConfiguration : gkStationConfigurationList) {
            NodeDTOV2 nodeDTOV2 = new NodeDTOV2();
            String nodeName = new String();
            for (GkStation gkStation : gkStations) {
                if (gkStation.getId().longValue() == gkStationConfiguration.getStationId().longValue()) {
                    if (gkStationConfiguration.getType() == 1) {
                        nodeName = "DB_RECIPE." + ((gkStation.getCode() == null || gkStation.getCode().equals("")) ? "" : (gkStation.getCode() + ".")) + gkStationConfiguration.getVariableName();
                    }
                    if (gkStationConfiguration.getType() == 2) {
                        for (GkProductionLineVo gkProductionLineVo : gkProductionLineVos) {
                            if (gkStation.getProductionLineId().longValue() == gkProductionLineVo.getId().longValue()) {
                                nodeName = gkProductionLineVo.getCode() + "." + ((gkStation.getCode() == null || gkStation.getCode().equals("")) ? "" : (gkStation.getCode() + ".")) + gkStationConfiguration.getVariableName();
                            }
                        }
                    }
                    if (gkStationConfiguration.getType() == 3) {
                        nodeName = "data_pc_plc.pc_reply." + gkStationConfiguration.getVariableName();
                    }
                    if (gkStationConfiguration.getType() == 4) {
                        nodeName = "data_pc_plc.plc_request." + gkStationConfiguration.getVariableName();
                    }
                }
            }
            if (gkStationConfiguration.getDataType().equals("boolean")) {
                gkStationConfiguration.setDataType("bool");
            }
            gkStationConfiguration.setDataType(gkStationConfiguration.getDataType().toUpperCase());
            nodeDTOV2.setNodeName(nodeName);
            nodeDTOV2.setNodeType(gkStationConfiguration.getDataType());
            Object obj = null;
            for (GkStationConfigureTemplateInfo gkStationConfigureTemplateInfo : gkStationConfigureTemplateInfos) {
                if (gkStationConfigureTemplateInfo.getStationConfigurationId().longValue() == gkStationConfiguration.getId().longValue()
                        &&gkStationConfiguration.getType()==1) {
                    if (gkStationConfiguration.getVariableName().equals("ProductType")){
                        productName = gkStationConfigureTemplateInfo.getValue();
                    }
                    if (gkStationConfiguration.getDataType().equals("BOOL")) {
                        if (StringUtils.equals(gkStationConfigureTemplateInfo.getValue(), "true")) {
                            obj = Boolean.TRUE;
                        } else {
                            obj = Boolean.FALSE;
                        }
                    } else if (gkStationConfiguration.getDataType().equals("STRING")) {
                        if (com.sgl.common.utils.StringUtils.isEmpty(gkStationConfigureTemplateInfo.getValue())) {
                            obj = null;
                        } else {
                            obj = gkStationConfigureTemplateInfo.getValue();
                        }
                    } else if (StringUtils.isEmpty(gkStationConfigureTemplateInfo.getValue())) {
                        obj = null;
                    } else {
                        Pattern pattern = Pattern.compile("^[-+]?[0-9]+(\\.[0-9]+)?$");
                        Matcher isNum = pattern.matcher(gkStationConfigureTemplateInfo.getValue());
                        if (!isNum.matches()) {
                            return AjaxResult.error(gkStationConfiguration.getDisplayName() + "输入值类型不匹配");
                        }
                        if (gkStationConfiguration.getDataType().equals("FLOAT")) {
                            obj = Float.parseFloat(gkStationConfigureTemplateInfo.getValue());
                        } else {
                            obj = Integer.parseInt(gkStationConfigureTemplateInfo.getValue());
                        }
                    }
                }
            }
            map.put(nodeName, obj);
            nodeDTOV2.setNodeValue(obj);
            if (CollUtil.isNotEmpty(fileNodeList)){
                for (Node node : fileNodeList) {
                    if (node.getDisplayName().equals(nodeName)) {
                        nodeDTOV2.setNodeId(node.getNodeId());
                    }
                }
            }
            log.info("设置属性：{}", nodeDTOV2.toString());
            writeNodeList.add(nodeDTOV2);
        }
        opcUaWriteReqV2.setWriteNodeList(writeNodeList);
        Ret<List<NodeDTOV2>> listRet = null;
        String s = null;
        try {
            if (communication.equals("socket")) {
                BufferedWriter bufferedWriter = ScheduledTask.bufferedWriter;
                BufferedReader bufferedReader = ScheduledTask.bufferedReader;
                SocketDataVo socketDataVo = new SocketDataVo();
                socketDataVo.setUid(opcUaWriteReqV2.getUid());
                List<ServiceData> nodeList = new ArrayList<>();
                for (NodeDTOV2 nodeDTOV2 : writeNodeList) {
                    ServiceData serviceData = new ServiceData();
                    serviceData.setNodeName(nodeDTOV2.getNodeName());
                    serviceData.setDisplayName(nodeDTOV2.getNodeName());
                    serviceData.setNodeValue(nodeDTOV2.getNodeValue());
                    serviceData.setNodeType(nodeDTOV2.getNodeType());
                    nodeList.add(serviceData);
                }
                socketDataVo.setNodeList(nodeList);
                bufferedWriter.write("setData?" + JSON.toJSONString(socketDataVo) + "\n");
                bufferedWriter.flush();
                s = bufferedReader.readLine();
            } else if (communication.equals("plc")) {
                if (!OpcUATool.isConnect(opcUaServiceV2, opcUaWriteReqV2)) {
                    int i = 0;
                    for (i=0 ; i < 10; i++) {
                        if (OpcUATool.isConnect(opcUaServiceV2,opcUaWriteReqV2)){
                            break;
                        }
                        Thread.sleep(200);
                    }
                    if (i==10) {
                        return AjaxResult.error("plc连接异常，请重新下发参数");
                    }
                }
                opcUaWriteReqV2 = OpcUATool.valueIsChange(opcUaServiceV2, opcUaWriteReqV2);
                for (int i = 0; i < 10; i++) {
                    listRet = opcUaServiceV2.writeData(opcUaWriteReqV2);
                    if (listRet!=null){
                        break;
                    }
                }

            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        // todo 模板一键配置模板参数下发记录
        Map<Long, List<GkStation>> listMap = gkStations.parallelStream().collect(Collectors.groupingBy(GkStation::getProductionLineId));
        GkSettingLog gkSettingLog = new GkSettingLog();
        String setStation = new String();
        for (GkProductionLineVo gkProductionLineVo : gkProductionLineVos) {
            List<GkStation> gkStations2 = listMap.get(gkProductionLineVo.getId());
            if (CollUtil.isNotEmpty(gkStations2)) {
                List<String> stationNames = gkStations2.stream().filter(gk -> StringUtils.isNotEmpty(gk.getName())).map(GkStation::getName).collect(Collectors.toList());
                String join = StringUtils.join(stationNames, ",");
                setStation += gkProductionLineVo.getName()+":"+"("+join+");";
            }
        }
        gkSettingLog.setTemplateId(templateId);
        gkSettingLog.setProductName(productName);
        gkSettingLog.setSetStation(setStation);
        gkSettingLogService.add(gkSettingLog);
//        if (StringUtils.isNotEmpty(productName)) {
//            List<GkReservedInfo> gkReservedInfoList = new ArrayList<>();
//            GkReservedInfo gkReservedInfo = new GkReservedInfo();
//            gkReservedInfo.setId(1l);
//            gkReservedInfo.setValue(productName);
//            gkReservedInfoList.add(gkReservedInfo);
//            GkProduct gkProduct = new GkProduct();
//            gkProduct.setTemplateName(productName);
//            List<GkProduct> list = gkProductMapper.list(gkProduct);
//            GkReservedInfo gkReservedInfo1 = new GkReservedInfo();
//            if (CollUtil.isNotEmpty(list)){
//                for (GkProduct product : list) {
//                    gkReservedInfo1.setValue(product.getCode());
//                    gkReservedInfo1.setId(2l);
//                }
//            }
//            gkReservedInfoList.add(gkReservedInfo1);
//            int row = gkReservedInfoMapper.editList(gkReservedInfoList);
//        }
        if (listRet == null && s == null) {
            return AjaxResult.error("下发参数失败，请重新下发参数");
        }
        if (s == null && listRet.getData() == null) {
            return AjaxResult.error(listRet.getMsg());
        }
        List<GkStationConfiguration> gkStationConfigurations = new ArrayList<>();


        List<NodeDTOV2> data = new ArrayList<>();
        if (communication.equals("socket")) {
            SocketDataVo socketDataVo = JSON.parseObject(s, SocketDataVo.class);
            List<ServiceData> nodeList = socketDataVo.getNodeList();
            for (ServiceData serviceData : nodeList) {
                NodeDTOV2 nodeDTOV2 = new NodeDTOV2();
                nodeDTOV2.setNodeValue(serviceData.getNodeValue());
                nodeDTOV2.setNodeType(serviceData.getNodeType());
                nodeDTOV2.setNodeName(serviceData.getNodeName());
                nodeDTOV2.setNodeId(serviceData.getNodeId());
                nodeDTOV2.setDisplayName(serviceData.getDisplayName());
                nodeDTOV2.setStatusCode(0l);
                data.add(nodeDTOV2);
            }
        } else if (communication.equals("plc")) {
            data = listRet.getData();
        }
        for (NodeDTOV2 datum : data) {
            if (datum.getStatusCode().intValue() != 0) {
                for (GkStationConfiguration gkStationConfiguration : gkStationConfigurationList) {
                    String nodeName = new String();
                    for (GkStation gkStation : gkStations) {
                        if (gkStation.getId().longValue() == gkStationConfiguration.getStationId().longValue()) {
                            if (gkStationConfiguration.getType() == 1) {
                                nodeName = "DB_RECIPE." + ((gkStation.getCode() == null || gkStation.getCode().equals("")) ? "" : (gkStation.getCode() + ".")) + gkStationConfiguration.getVariableName();
                            }
                            if (gkStationConfiguration.getType() == 2) {
                                for (GkProductionLineVo gkProductionLineVo : gkProductionLineVos) {
                                    if (gkStation.getProductionLineId().longValue() == gkProductionLineVo.getId().longValue()) {
                                        nodeName = gkProductionLineVo.getCode() + "." + ((gkStation.getCode() == null || gkStation.getCode().equals("")) ? "" : (gkStation.getCode() + ".")) + gkStationConfiguration.getVariableName();
                                    }
                                }
                            }
                            if (gkStationConfiguration.getType() == 3) {
                                nodeName = "data_pc_plc.pc_reply." + gkStationConfiguration.getVariableName();
                            }
                            if (gkStationConfiguration.getType() == 4) {
                                nodeName = "data_pc_plc.plc_request." + gkStationConfiguration.getVariableName();
                            }
                        }
                    }
                    if (datum.getNodeName().equals(nodeName)) {
                        // 修改失败则不修改默认值
                        gkStationConfiguration.setDataType(null);
                        gkStationConfiguration.setStatusMsg(datum.getStatusMsg());
                        gkStationConfigurations.add(gkStationConfiguration);
                    }
                }
            }
        }
        GkStationConfigureTemplate gkStationConfigureTemplate1 = new GkStationConfigureTemplate();
        gkStationConfigureTemplate1.setId(templateId);
        try {
            // todo 模板一键配置延时定位
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        if (gkStationConfigurations.size() > 0) {
            gkStationConfigureTemplate1.setConfigureType(StationDict.PARTIALSETTINGS.value);
            gkStationConfigureTemplateMapper.edit(gkStationConfigureTemplate1);
            List<Long> collect = gkStationConfigurations.stream().map(GkStationConfiguration::getStationId).distinct().collect(Collectors.toList());
            List<String> stationNames = new ArrayList<>();
            for (GkStation gkStation : gkStations) {
                int flag = 0;
                for (Long aLong : collect) {
                    if (aLong.longValue() == gkStation.getId().longValue()) {
                        flag = 1;
                    }
                }
                if (flag == 0) {
                    stationNames.add(gkStation.getName());
                }
            }
            return AjaxResult.success("部分工位设置成功：{}", stationNames.toString());
        } else {
            gkStationConfigureTemplate1.setConfigureType(StationDict.CONFIGURED.value);
            gkStationConfigureTemplateMapper.edit(gkStationConfigureTemplate1);
        }
        return AjaxResult.success("设置成功");
    }

    @Override
    public AjaxResult editList(SaveTemplateVo saveTemplateVo) {
        List<GkStationConfiguration> gkStationConfigurations = saveTemplateVo.getGkStationConfigurations();
        for (GkStationConfiguration gkStationConfiguration : gkStationConfigurations) {
            if (gkStationConfiguration.getSaveValue()==null) {
                gkStationConfiguration.setSaveValue("");
            }
        }
        int row = gkStationConfigureTemplateInfoMapper.editList(saveTemplateVo.getTemplateId(), gkStationConfigurations);
        if (row > 0) {
            GkStationConfigureTemplate gkStationConfigureTemplate = new GkStationConfigureTemplate();
            gkStationConfigureTemplate.setId(saveTemplateVo.getTemplateId());
            gkStationConfigureTemplate.setConfigureType(StationDict.SAVEUNCONFIGURED.value);
            gkStationConfigureTemplateMapper.edit(gkStationConfigureTemplate);
            gkStationConfigurationMapper.editList(gkStationConfigurations.toArray(new GkStationConfiguration[0]));
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    @Override
    @Transactional
    public AjaxResult editConfiguration(TemplateSaveParamInfosVo templateSaveParamInfosVo) {
        if (templateSaveParamInfosVo.getTempConfigName()==null){
            templateSaveParamInfosVo.setTempConfigName("");
        }
        int row = gkStationConfigureTemplateInfoMapper.editConfigNameById(templateSaveParamInfosVo);
        if (row>0){
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    @Override
    public int removeByProductionLineIds(Long[] ids) {
        List<GkStationConfigureTemplate> gkStationConfigureTemplates = gkStationConfigureTemplateMapper.selectInfoByProductionLineIds(ids);
        List<Long> collect = gkStationConfigureTemplates.stream().map(GkStationConfigureTemplate::getId).collect(Collectors.toList());
        AjaxResult ajaxResult = AjaxResult.success();
        if (collect != null && collect.size() > 0) {
            ajaxResult = removeByIds(collect.toArray(new Long[0]));
        }
        if (Integer.parseInt(ajaxResult.get("code").toString()) == 200) {
            return 1;
        }
        return 0;
    }

    @Override
    public AjaxResult setParametersByTemplateName(GkStationConfigureTemplate gkStationConfigureTemplate) {
        if (StringUtils.isEmpty(gkStationConfigureTemplate.getName())) {
            return AjaxResult.success("需传入模板名称");
        }
        gkStationConfigureTemplate.setProductionLineId(null);
        List<GkStationConfigureTemplate> list = gkStationConfigureTemplateMapper.list(gkStationConfigureTemplate);
        if (list == null || list.size() == 0) {
            return AjaxResult.success("无可设置模板");
        }
        List<Long> templateIds = list.stream().map(GkStationConfigureTemplate::getId).collect(Collectors.toList());
        List<GkStationConfigureTemplateInfo> gkStationConfigureTemplateInfos = gkStationConfigureTemplateInfoMapper.selectInfoByConfigureTemplateIds(templateIds);
        gkStationConfigureTemplateInfos = gkStationConfigureTemplateInfos.stream().filter(gkStationTemp->gkStationTemp.getTempToUse()!=0).collect(Collectors.toList());
        List<Long> productionLineIds = list.stream().map(GkStationConfigureTemplate::getProductionLineId).distinct().collect(Collectors.toList());
        List<GkStation> gkStations = gkStationMapper.selectByProductionIds(productionLineIds);
        List<Long> stationIds = new ArrayList<>();
        List<Long> signalCommunicationIds = new ArrayList<>();
        for (GkStation gkStation : gkStations) {
            stationIds.add(gkStation.getId());
            signalCommunicationIds.add(gkStation.getSignalCommunicationId());
        }
        signalCommunicationIds = signalCommunicationIds.stream().distinct().collect(Collectors.toList());
        List<GkStationConfiguration> gkStationConfigurationList = gkStationConfigurationMapper.selectInfoByType1Stations(stationIds);
        List<GkProductionLineVo> gkProductionLineVos = gkProductionLineMapper.selectInfoByIds(productionLineIds);
        List<GkSignalCommunication> gkSignalCommunications = gkSignalCommunicationMapper.selectInfoByIds(signalCommunicationIds);
        Map<Long, List<GkStationConfiguration>> gkStationConfigurationByStationIdMap = gkStationConfigurationList.parallelStream().collect(Collectors.groupingBy(GkStationConfiguration::getStationId));
        Map<Long, List<GkStationConfigureTemplateInfo>> templateInfoByIdMap = gkStationConfigureTemplateInfos.parallelStream().collect(Collectors.groupingBy(GkStationConfigureTemplateInfo::getConfigureTemplateId));
        List<OpcUaWriteReqV2> opcUaWriteReqV2List = new ArrayList<>();
        Map<String, Map<String, Object>> listMap = new HashMap<>();
        List<GkStation> stationNoBindingList = new ArrayList<>();
        String productName = "";
        OpcUaList opcUaList = ReadOpcUaNodeInfoTool.GetOpcUaList();
        List<OpcUa> uaList = opcUaList.getOpcUaList();
        for (GkSignalCommunication gkSignalCommunication : gkSignalCommunications) {
            List<Node> fileNodeList = new ArrayList<>();
            for (OpcUa opcUa : uaList) {
                if (opcUa.getUid().equals(gkSignalCommunication.getCommunicationProtocol())){
                    fileNodeList = opcUa.getNodeList();
                }
            }
            Map<String, Object> map = new HashMap<>();
            OpcUaWriteReqV2 opcUaWriteReqV2 = new OpcUaWriteReqV2();
            opcUaWriteReqV2.setUid(gkSignalCommunication.getCommunicationProtocol());
            ArrayList<NodeDTOV2> writeNodeList = new ArrayList<>();
            for (GkStation gkStation : gkStations) {
                if (gkStation.getSignalCommunicationId() == null) {
                    stationNoBindingList.add(gkStation);
                }
                if (gkStation.getSignalCommunicationId() != null && gkStation.getSignalCommunicationId().longValue() == gkSignalCommunication.getId().longValue()) {
                    List<GkStationConfiguration> gkStationConfigurationList1 = gkStationConfigurationByStationIdMap.get(gkStation.getId());
                    Long templateID = null;
                    // 根据名称查询的模板id每条产线不会重复，因为模板名称在同一产线内不允许重复
                    for (GkStationConfigureTemplate stationConfigureTemplate : list) {
                        if (stationConfigureTemplate.getProductionLineId().longValue() == gkStation.getProductionLineId().longValue()) {
                            templateID = stationConfigureTemplate.getId();
                        }
                    }
                    List<GkStationConfigureTemplateInfo> gkStationConfigureTemplateInfos1 = templateInfoByIdMap.get(templateID);
                    for (GkStationConfiguration gkStationConfiguration : gkStationConfigurationList1) {
                        if (gkStationConfiguration.getType()==1) {
                            NodeDTOV2 nodeDTOV2 = new NodeDTOV2();
                            for (GkStationConfigureTemplateInfo gkStationConfigureTemplateInfo : gkStationConfigureTemplateInfos1) {
                                if (gkStationConfiguration.getId().longValue() == gkStationConfigureTemplateInfo.getStationConfigurationId().longValue()) {
                                    gkStationConfiguration.setSaveValue(gkStationConfigureTemplateInfo.getValue());
                                    gkStationConfiguration.setTempToUse(gkStationConfigureTemplateInfo.getTempToUse());
                                }
                            }
                            if (gkStationConfiguration.getVariableName().equals("ProductType")) {
                                productName = gkStationConfiguration.getSaveValue();
                            }
                            String nodeName = new String();
                            if (gkStationConfiguration.getType() == 1) {
                                nodeName = "DB_RECIPE." + ((gkStation.getCode() == null || gkStation.getCode().equals("")) ? "" : (gkStation.getCode() + ".")) + gkStationConfiguration.getVariableName();
                            }
                            if (gkStationConfiguration.getType() == 2) {
                                for (GkProductionLineVo gkProductionLineVo : gkProductionLineVos) {
                                    if (gkStation.getProductionLineId().longValue() == gkProductionLineVo.getId().longValue()) {
                                        nodeName = gkProductionLineVo.getCode() + "." + ((gkStation.getCode() == null || gkStation.getCode().equals("")) ? "" : (gkStation.getCode() + ".")) + gkStationConfiguration.getVariableName();
                                    }
                                }
                            }
                            if (gkStationConfiguration.getType() == 3) {
                                nodeName = "data_pc_plc.pc_reply." + gkStationConfiguration.getVariableName();
                            }
                            if (gkStationConfiguration.getType() == 4) {
                                nodeName = "data_pc_plc.plc_request." + gkStationConfiguration.getVariableName();
                            }
                            nodeDTOV2.setNodeName(nodeName);
                            if (gkStationConfiguration.getDataType().equals("boolean")) {
                                gkStationConfiguration.setDataType("bool");
                            }
                            gkStationConfiguration.setDataType(gkStationConfiguration.getDataType().toUpperCase());
                            nodeDTOV2.setNodeType(gkStationConfiguration.getDataType());

                            Object obj = new Object();
                            if (gkStationConfiguration.getDataType().equals("BOOL")) {
                                if (StringUtils.equals(gkStationConfiguration.getSaveValue(), "true")) {
                                    obj = Boolean.TRUE;
                                } else {
                                    obj = Boolean.FALSE;
                                }
                            } else if (gkStationConfiguration.getDataType().equals("STRING")) {
                                if (com.sgl.common.utils.StringUtils.isEmpty(gkStationConfiguration.getSaveValue())) {
                                    obj = null;
                                } else {
                                    obj = gkStationConfiguration.getSaveValue();
                                }
                            } else if (StringUtils.isEmpty(gkStationConfiguration.getSaveValue())) {
                                obj = null;
                            } else {
                                Pattern pattern = Pattern.compile("^[-+]?[0-9]+(\\.[0-9]+)?$");
                                Matcher isNum = pattern.matcher(gkStationConfiguration.getSaveValue());
                                if (!isNum.matches()) {
                                    return AjaxResult.error(gkStationConfiguration.getDisplayName() + "输入值类型不匹配");
                                }
                                if (gkStationConfiguration.getDataType().equals("FLOAT")) {
                                    obj = Float.parseFloat(gkStationConfiguration.getSaveValue());
                                } else {
                                    obj = Integer.parseInt(gkStationConfiguration.getSaveValue());
                                }
                            }
                            map.put(nodeName, obj);
                            nodeDTOV2.setNodeValue(obj);
                            if (gkStationConfiguration.getTempToUse()!=null&&gkStationConfiguration.getTempToUse()==1) {
                                if (CollUtil.isNotEmpty(fileNodeList)){
                                    for (Node node : fileNodeList) {
                                        if (node.getDisplayName().equals(nodeName)) {
                                            nodeDTOV2.setNodeId(node.getNodeId());
                                        }
                                    }
                                }
                                log.info("设置属性：{}", nodeDTOV2.toString());
                                writeNodeList.add(nodeDTOV2);
                            }
                        }
                    }
                }
            }
            listMap.put(opcUaWriteReqV2.getUid(), map);
            opcUaWriteReqV2.setWriteNodeList(writeNodeList);
            opcUaWriteReqV2List.add(opcUaWriteReqV2);
        }
        if (opcUaWriteReqV2List.size() == 0) {
            return AjaxResult.error("无设置属性");
        }
        for (OpcUaWriteReqV2 opcUaWriteReqV2 : opcUaWriteReqV2List) {
            List<NodeDTOV2> writeNodeList = opcUaWriteReqV2.getWriteNodeList();
            Ret<List<NodeDTOV2>> listRet = null;
            String s = null;
            String uid = opcUaWriteReqV2.getUid();
            try {
                if (communication.equals("socket")) {
                    BufferedWriter bufferedWriter = ScheduledTask.bufferedWriter;
                    BufferedReader bufferedReader = ScheduledTask.bufferedReader;
                    SocketDataVo socketDataVo = new SocketDataVo();
                    socketDataVo.setUid(uid);
                    List<ServiceData> nodeList = new ArrayList<>();
                    for (NodeDTOV2 nodeDTOV2 : writeNodeList) {
                        ServiceData serviceData = new ServiceData();
                        serviceData.setNodeName(nodeDTOV2.getNodeName());
                        serviceData.setDisplayName(nodeDTOV2.getNodeName());
                        serviceData.setNodeValue(nodeDTOV2.getNodeValue());
                        serviceData.setNodeType(nodeDTOV2.getNodeType());
                        nodeList.add(serviceData);
                    }
                    socketDataVo.setNodeList(nodeList);
                    bufferedWriter.write("setData?" + JSON.toJSONString(socketDataVo) + "\n");
                    bufferedWriter.flush();
                    s = bufferedReader.readLine();
                    if (s.equals("NO")){
                        return AjaxResult.error("设置失败");
                    }
                }
                if (communication.equals("plc")) {
                    if (!OpcUATool.isConnect(opcUaServiceV2, opcUaWriteReqV2)) {
                        int i = 0;
                        for (i=0 ; i < 10; i++) {
                            if (OpcUATool.isConnect(opcUaServiceV2,opcUaWriteReqV2)){
                                break;
                            }
                            Thread.sleep(200);
                        }
                        if (i==10) {
                            return AjaxResult.error("plc连接异常,请重新下发参数");
                        }
                    }
                    List<NodeDTOV2> writeNodeList1 = opcUaWriteReqV2.getWriteNodeList();
                    opcUaWriteReqV2 = OpcUATool.valueIsChange(opcUaServiceV2, opcUaWriteReqV2);
                    if (CollUtil.isEmpty(opcUaWriteReqV2.getWriteNodeList())){
//                        OpcUaReadReqV2 opcUaReadReqV2 = new OpcUaReadReqV2();
//                        opcUaReadReqV2.setUid(opcUaWriteReqV2.getUid());
//                        Ret<BatchReadDTO> batchReadDTORet = opcUaServiceV2.readData(opcUaReadReqV2);
                        ReadByNodeReq readByNodeReq = new ReadByNodeReq();
                        readByNodeReq.setUid(opcUaWriteReqV2.getUid());
                        readByNodeReq.setNodeDTOV2List(writeNodeList1);
                        Ret<BatchReadDTO> batchReadDTORet = opcUaServiceV2.readDataByNodeList(readByNodeReq);
                        listRet = new Ret<>(batchReadDTORet.getData().getDtoList());
                        listRet.setMsg(batchReadDTORet.getMsg());
                        listRet.setCode(batchReadDTORet.getCode());
                    }else {
                        for (int i = 0; i < 10; i++) {
                            listRet = opcUaServiceV2.writeData(opcUaWriteReqV2);
                            if (listRet!=null){
                                break;
                            }
                        }
                    }
                }
            } catch (Exception e) {
                log.error(e.getMessage());
            }
            if (listRet == null && s == null) {
                return AjaxResult.error("下发参数失败，请重新下发参数");
            }
            if (s == null && listRet.getData() == null) {
                return AjaxResult.error(listRet.getMsg());
            }
            List<GkStationConfiguration> gkStationConfigurations = new ArrayList<>();


            List<NodeDTOV2> data = new ArrayList<>();
            if (communication.equals("socket")) {
                SocketDataVo socketDataVo = JSON.parseObject(s, SocketDataVo.class);
                List<ServiceData> nodeList = socketDataVo.getNodeList();
                for (ServiceData serviceData : nodeList) {
                    NodeDTOV2 nodeDTOV2 = new NodeDTOV2();
                    nodeDTOV2.setNodeValue(serviceData.getNodeValue());
                    nodeDTOV2.setNodeType(serviceData.getNodeType());
                    nodeDTOV2.setNodeName(serviceData.getNodeName());
                    nodeDTOV2.setNodeId(serviceData.getNodeId());
                    nodeDTOV2.setDisplayName(serviceData.getDisplayName());
                    nodeDTOV2.setStatusCode(0l);
                    data.add(nodeDTOV2);
                }
            }
            if (communication.equals("plc")) {
                data = listRet.getData();
            }
            for (NodeDTOV2 datum : data) {
                if (datum.getStatusCode().intValue() != 0) {
                    for (GkStationConfiguration gkStationConfiguration : gkStationConfigurationList) {
                        String nodeName = new String();
                        for (GkStation gkStation : gkStations) {
                            if (gkStation.getId().longValue() == gkStationConfiguration.getStationId().longValue()) {
                                if (gkStationConfiguration.getType() == 1) {
                                    nodeName = "DB_RECIPE." + ((gkStation.getCode() == null || gkStation.getCode().equals("")) ? "" : (gkStation.getCode() + ".")) + gkStationConfiguration.getVariableName();
                                }
                                if (gkStationConfiguration.getType() == 2) {
                                    for (GkProductionLineVo gkProductionLineVo : gkProductionLineVos) {
                                        if (gkStation.getProductionLineId().longValue() == gkProductionLineVo.getId().longValue()) {
                                            nodeName = gkProductionLineVo.getCode() + "." + ((gkStation.getCode() == null || gkStation.getCode().equals("")) ? "" : (gkStation.getCode() + ".")) + gkStationConfiguration.getVariableName();
                                        }
                                    }
                                }
                                if (gkStationConfiguration.getType() == 3) {
                                    nodeName = "data_pc_plc.pc_reply." + gkStationConfiguration.getVariableName();
                                }
                                if (gkStationConfiguration.getType() == 4) {
                                    nodeName = "data_pc_plc.plc_request." + gkStationConfiguration.getVariableName();
                                }
                            }
                        }
                        if (datum.getNodeName().equals(nodeName)) {
                            // 修改失败则不修改默认值
                            gkStationConfiguration.setDataType(null);
                            gkStationConfiguration.setStatusMsg(datum.getStatusMsg());
                            gkStationConfigurations.add(gkStationConfiguration);
                        }
                    }
                }
            }
            GkStationConfigureTemplate gkStationConfigureTemplate1 = new GkStationConfigureTemplate();
            Long templateId = null;
            for (GkSignalCommunication gkSignalCommunication : gkSignalCommunications) {
                if (gkSignalCommunication.getCommunicationProtocol().equals(uid)) {
                    for (GkStationConfigureTemplate stationConfigureTemplate : list) {
                        for (GkStation gkStation : gkStations) {
                            if (gkStation.getProductionLineId().longValue() == stationConfigureTemplate.getProductionLineId().longValue()
                                    && gkStation.getSignalCommunicationId().longValue() == gkSignalCommunication.getId().longValue()) {
                                templateId = stationConfigureTemplate.getId();
                                break;
                            }
                        }
                        if (templateId != null) {
                            break;
                        }
                    }
                    if (templateId != null) {
                        break;
                    }
                }
            }
            gkStationConfigureTemplate1.setId(templateId);
            if (gkStationConfigurations.size() > 0) {
                gkStationConfigureTemplate1.setConfigureType(StationDict.PARTIALSETTINGS.value);
                gkStationConfigureTemplateMapper.edit(gkStationConfigureTemplate1);
                List<Long> collect = gkStationConfigurations.stream().map(GkStationConfiguration::getStationId).distinct().collect(Collectors.toList());
                List<String> stationNames = new ArrayList<>();
                for (GkStation gkStation : gkStations) {
                    int flag = 0;
                    for (Long aLong : collect) {
                        if (aLong.longValue() == gkStation.getId().longValue()) {
                            flag = 1;
                        }
                    }
                    if (flag == 0) {
                        stationNames.add(gkStation.getName());
                    }
                }
                try {
                    Thread.sleep(6000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                return AjaxResult.success("部分工位设置成功：{}", stationNames.toString());
            } else {
                gkStationConfigureTemplate1.setConfigureType(StationDict.CONFIGURED.value);
                gkStationConfigureTemplateMapper.edit(gkStationConfigureTemplate1);
            }
        }
        // todo 根据模板名称 模板参数下发记录
        Map<Long, List<GkStation>> listMap1 = gkStations.parallelStream().collect(Collectors.groupingBy(GkStation::getProductionLineId));
        GkSettingLog gkSettingLog = new GkSettingLog();
        String setStation = new String();
        for (GkProductionLineVo gkProductionLineVo : gkProductionLineVos) {
            List<GkStation> gkStations2 = listMap1.get(gkProductionLineVo.getId());
            if (CollUtil.isNotEmpty(gkStations2)) {
                List<String> stationNames = gkStations2.stream().filter(gk -> StringUtils.isNotEmpty(gk.getName())).map(GkStation::getName).collect(Collectors.toList());
                String join = StringUtils.join(stationNames, ",");
                setStation += gkProductionLineVo.getName()+":"+"("+join+");";
            }
        }
        for (Long templateId : templateIds) {
            gkSettingLog.setTemplateId(templateId);
        }
        gkSettingLog.setProductName(productName);
        gkSettingLog.setSetStation(setStation);
        gkSettingLogService.add(gkSettingLog);
        if (StringUtils.isNotEmpty(gkStationConfigureTemplate.getName())) {
            List<GkReservedInfo> gkReservedInfoList = new ArrayList<>();
            GkReservedInfo gkReservedInfo = new GkReservedInfo();
            GkProduct gkProduct = new GkProduct();
            gkProduct.setTemplateName(gkStationConfigureTemplate.getName());
            List<GkProduct> gkProducts = gkProductMapper.list(gkProduct);
            GkReservedInfo gkReservedInfo1 = new GkReservedInfo();
            if (CollUtil.isNotEmpty(gkProducts)){
                for (GkProduct product : gkProducts) {
                    gkReservedInfo.setId(1l);
                    gkReservedInfo.setValue(product.getName());
                    gkReservedInfo1.setValue(product.getCode());
                    gkReservedInfo1.setId(2l);
                }
            }
            gkReservedInfoList.add(gkReservedInfo);
            gkReservedInfoList.add(gkReservedInfo1);
            int row = gkReservedInfoMapper.editList(gkReservedInfoList);
        }
        try {
            // todo 根据模板名称设置参数延时定位
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        if (stationNoBindingList.size() > 0) {
            String join = StringUtils.join(stationNoBindingList.stream().map(GkStation::getName).collect(Collectors.toList()), ",");
            return AjaxResult.success("设置成功，有未绑定通讯协议工位：" + join);
        }
        return AjaxResult.success("设置成功");
    }

    @Override
    public AjaxResult getSaveParamByStationIdAndName(Long stationId, Long tempId) {
        if (stationId==null||tempId==null){
            return AjaxResult.error("工位id或模板id必传");
        }
        GkStationConfiguration gkStationConfiguration = new GkStationConfiguration();
        gkStationConfiguration.setStationId(stationId);
        // 保存参数
        List<GkStationConfigurationVo> saveParams = gkStationConfigurationMapper.list(gkStationConfiguration);
        if (CollUtil.isEmpty(saveParams)) {
            return AjaxResult.success();
        }
        List<Long> configurationIds = saveParams.stream().map(GkStationConfigurationVo::getId).collect(Collectors.toList());
        List<GkStationConfigureTemplateInfo> gkStationConfigureTemplateInfos = gkStationConfigureTemplateInfoMapper.selectInfoByTempIdAndConfigIds(tempId, configurationIds);
        if (CollUtil.isNotEmpty(gkStationConfigureTemplateInfos)) {
            List<TemplateSaveParamInfosVo> templateSaveParamInfosVos = new ArrayList<>();
            for (GkStationConfigureTemplateInfo gkStationConfigureTemplateInfo : gkStationConfigureTemplateInfos) {
                TemplateSaveParamInfosVo templateSaveParamInfosVo = new TemplateSaveParamInfosVo();
                templateSaveParamInfosVo.setTempInfoId(gkStationConfigureTemplateInfo.getId());
                templateSaveParamInfosVo.setTempToUse(gkStationConfigureTemplateInfo.getTempToUse());
                for (GkStationConfigurationVo saveParam : saveParams) {
                    if (saveParam.getId().longValue() == gkStationConfigureTemplateInfo.getStationConfigurationId().longValue()) {
                        BeanUtils.copyProperties(saveParam, templateSaveParamInfosVo, new String[]{"tempInfoId", "tempToUse"});
                    }
                }
                templateSaveParamInfosVos.add(templateSaveParamInfosVo);
            }
            return AjaxResult.success(templateSaveParamInfosVos);
        }
        return AjaxResult.success(new ArrayList<>());
    }

    @Override
    public AjaxResult editTempInfoToUse(TemplateSaveParamInfosVo templateSaveParamInfosVo) {
        GkStationConfigureTemplateInfo gkStationConfigureTemplateInfo = new GkStationConfigureTemplateInfo();
        gkStationConfigureTemplateInfo.setId(templateSaveParamInfosVo.getTempInfoId());
        gkStationConfigureTemplateInfo.setTempToUse(templateSaveParamInfosVo.getTempToUse());
        gkStationConfigureTemplateInfoMapper.editTempInfo(gkStationConfigureTemplateInfo);
        return AjaxResult.success();
    }

    @Override
    public void exportByTempName(String tempName, HttpServletResponse response) {
        List<GkStationConfigureTemplate> gkStationConfigureTemplates = gkStationConfigureTemplateMapper.selectInfoByNames(Collections.singletonList(tempName));
        if (CollUtil.isEmpty(gkStationConfigureTemplates)){
            return;
        }
        List<Long> tempIds = gkStationConfigureTemplates.stream().map(GkStationConfigureTemplate::getId).collect(Collectors.toList());
        List<GkStationConfigureTemplateInfo> gkStationConfigureTemplateInfos = gkStationConfigureTemplateInfoMapper.selectInfoByConfigureTemplateIds(tempIds);
//        if (gks)
        // 获取到模板保存的数据
        gkStationConfigureTemplateInfos = gkStationConfigureTemplateInfos.stream().filter(gkSCTI -> gkSCTI.getTempToUse() != 0).collect(Collectors.toList());

        List<Long> stationIds = new ArrayList<>();
        Map<Long,List<Long>> tempStationIdsMap = new HashMap<>();
        for (GkStationConfigureTemplate gkStationConfigureTemplate : gkStationConfigureTemplates) {
            String[] split = gkStationConfigureTemplate.getStationIdList().split(",");
            List<Long> tempStationIds = new ArrayList<>();
            for (String s1 : split) {
                long e = Long.parseLong(s1);
                stationIds.add(e);
                tempStationIds.add(e);
            }
            tempStationIdsMap.put(gkStationConfigureTemplate.getId(),tempStationIds);
        }
        stationIds = stationIds.stream().distinct().collect(Collectors.toList());
        List<GkStation> gkStations = gkStationMapper.selectInfosByIds(stationIds);
        List<GkStationConfiguration> gkStationConfigurationList = gkStationConfigurationMapper.selectInfoByStations(stationIds.toArray(new Long[0]));
        // 所有的参数变量
        gkStationConfigurationList = gkStationConfigurationList.stream().filter(gkSCL->gkSCL.getType()==1).collect(Collectors.toList());
        Map<Long, List<GkStationConfiguration>> stationConfigIdsMap = gkStationConfigurationList.parallelStream().collect(Collectors.groupingBy(GkStationConfiguration::getStationId));
        String fileName = tempName ;
        List<Long> productIds = gkStationConfigureTemplates.stream().map(GkStationConfigureTemplate::getProductionLineId).collect(Collectors.toList());
        List<GkProductionLineVo> gkProductionLineVos = gkProductionLineMapper.selectInfoByIds(productIds);

        // 根据模板id吧保存的模板支分组
        Map<Long, List<GkStationConfigureTemplateInfo>> listMap = gkStationConfigureTemplateInfos.parallelStream().collect(Collectors.groupingBy(GkStationConfigureTemplateInfo::getConfigureTemplateId));
        // along 是模板id
        List<Map<String,Object>> map = new ArrayList<>();
        for (GkStationConfigureTemplate aLong : gkStationConfigureTemplates) {
            List<Long> tempStationIds = tempStationIdsMap.get(aLong.getId());
            String productionName = "";
            for (GkProductionLineVo gkProductionLineVo : gkProductionLineVos) {
                if (gkProductionLineVo.getId().longValue()==aLong.getProductionLineId()) {
                    productionName = gkProductionLineVo.getName();
                }
            }
            // 一个模板的所有工位
            for (Long tempStationId : tempStationIds) {
                // 一个工位一个表
                List<GkStationConfigurationVo> gkStationConfigurationVos = new ArrayList<>();
                String sheetName = new String();
                for (GkStation gkStation : gkStations) {
                    if (gkStation.getId().longValue()==tempStationId.longValue()) {
                        sheetName = productionName+"-"+gkStation.getName();
                        // 一个模板下面保存的所有参数变量
                        List<GkStationConfigureTemplateInfo> gkStationConfigureTemplateInfos1 = listMap.get(aLong.getId());
                        // 一工位下面所有的参数变量
                        List<GkStationConfiguration> gkStationConfigurations = stationConfigIdsMap.get(gkStation.getId());
                        for (GkStationConfigureTemplateInfo gkStationConfigureTemplateInfo : gkStationConfigureTemplateInfos1) {
                            for (GkStationConfiguration gkStationConfiguration : gkStationConfigurations) {
                                if (gkStationConfiguration.getId().longValue()==gkStationConfigureTemplateInfo.getStationConfigurationId().longValue()){
                                    GkStationConfigurationVo gkStationConfigurationVo = new GkStationConfigurationVo();
                                    if (StringUtils.isNotEmpty(gkStationConfigureTemplateInfo.getTempConfigName())){
                                        gkStationConfigurationVo.setDisplayName(gkStationConfigureTemplateInfo.getTempConfigName());
                                    }else {
                                        gkStationConfigurationVo.setDisplayName(gkStationConfiguration.getDisplayName());
                                    }
                                    gkStationConfigurationVo.setDefaultValue(gkStationConfigureTemplateInfo.getValue());
                                    gkStationConfigurationVos.add(gkStationConfigurationVo);
                                }
                            }
                        }
                    }
                }
                ExportParams exportParams = new ExportParams();
                sheetName = sheetName.replace("/","").replace("\\","");
                exportParams.setSheetName(sheetName);

                Map<String, Object> map1 = new HashMap<>();
                map1.put("title", exportParams);
                map1.put("entity", GkStationConfigurationVo.class);
                map1.put("data", gkStationConfigurationVos);
                map.add(map1);
            }
        }
        Workbook workbook = null;
        try {
            workbook = ExcelExportUtil.exportExcel(map, ExcelType.HSSF);
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".xls");
            response.setHeader("Cache-Control", "No-cache");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.flushBuffer();
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (workbook != null) {
                try {
                    //强行关流
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void setOpcUaServiceV2(OpcUaServiceV2 opcUaServiceV2) {
        this.opcUaServiceV2 = opcUaServiceV2;
    }
}
